 package controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.ModelAndView;

import entity.Category;
import entity.Comment;
import entity.Users;
import entity.Video;
import entity.VideoList;
import service.CategoryService;
import service.CommentService;
import service.UsersService;
import service.VideoListService;
import service.VideoService;
import util.PageUtil;
import net.sf.json.JSONObject;

@Controller
@RequestMapping("/video")
public class VideoController {

	@Autowired
	VideoService videoService;
	@Autowired
	UsersService usersService;
	@Autowired
	CategoryService categoryService;
	@Autowired
	VideoListService videoListService;
	@Autowired
	CommentService commentService;
	
	//上传视频
	@RequestMapping("/upload")
	public void video_upload(HttpServletRequest request, HttpServletResponse response) {
		List<String> filenames = new ArrayList<String>();
	//	String username = "123";
		String username = (String) request.getSession().getAttribute("username");
		
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
		//单个文件大小
		multipartResolver.setMaxUploadSize(1073741824);
		
		if(multipartResolver.isMultipart(request)) {
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			Iterator files = multipartRequest.getFileNames();
			while(files.hasNext()) {
				MultipartFile file = multipartRequest.getFile(files.next().toString());
				if(!file.getContentType().startsWith("video")) {
					continue;
				}
				if(!file.getOriginalFilename().equals("")) {
					String path = makeStorePath(request.getSession().   //文件的完整路径
							getServletContext().         				//
							getRealPath("/video-origin/"), username)   				//
							+ "\\" + file.getOriginalFilename();
					System.out.println(path);
					String path_base = path.substring(path.indexOf("video-origin"));  //基本地址
					try {
						// 文件上传：流的读写
						InputStream is = file.getInputStream();
						// 文件输出流
						FileOutputStream fos=new FileOutputStream(path);
						//设置缓冲区
						byte[] buffer=new byte[1024*1024];
						int len=-1;
						while((len=is.read(buffer))!=-1) {
							fos.write(buffer, 0, len);
						}
						// 释放资源
						is.close();
						fos.close();
						
						filenames.add(username + "\\" + file.getOriginalFilename()); //更新视频的路径
						//设置json数据格式
					    Map<String, Object> map = new HashMap<String, Object>();
					    Map<String, String> mapSecond = new HashMap<String, String>();
					    
//					    mapSecond.put("caption", "湄公河行动.TC1280清晰国语中英双字.mp4");
//					    mapSecond.put("key", "1");
//					    mapSecond.put("url", "http://localhost:8090/Book/upload/2016-12-21湄公河行动.TC1280清晰国语中英双字.mp4");
//					    mapSecond.put("size", "2807495401");
//					    
//					    map.put("videoUrl", "<video src='/upload/2016-12-21湄公河行动.TC1280清晰国语中英双字.mp4' controls='controls'>");
//					    map.put("initialPreviewConfig", mapSecond);
//					    map.put("initialPreview", "http://localhost:8090/Book/upload/2016-12-21湄公河行动.TC1280清晰国语中英双字.mp4");
					    
					    map.put("origin_url", path_base);
						//将json所需的包放到lib里面,将list转换为json
						//如果只是一个对象用JSONObject，如果是集合用JSONArray
				        JSONObject json=JSONObject.fromObject(map);
				        
				        request.setAttribute("origin_url", path_base);
				        //响应前台页面
				        response.setCharacterEncoding("utf-8");
				        response.setContentType("text/json");
				        PrintWriter out=response.getWriter();
				        out.println(json);//打印json，为了前台页面获取
				        out.flush();//刷新流
				        out.close();//关闭流
				        
				        
					} catch (Exception e) {
						e.printStackTrace(); 
					}
				}
			}
		}
		//request.setAttribute("filenames", filenames);
	}
	
	//提交完整的视频上传信息
	@RequestMapping("/upload_detail")
	public String video_upload_detail(Video video, HttpServletRequest request) {
		String username = (String) request.getSession().getAttribute("username"); //获取当前登陆用户的账号
//		String username = "as123456";
		video.setUser(usersService.findByUserName(username));
		video.setUploadTime(new Date()); 
		int result = 0;
		if(video.getVideoList().getId() == 0) {
			result = videoService.addNoListId(video);
		} else {
			result = videoService.add(video);
		}
		System.out.println("上传视频添加成功");
		return "redirect:to_upload";
	}
	
	//封装上传视频的路径
	public String makeStorePath(String storePath, String username) {
		Date date=new Date();
		DateFormat format=DateFormat.getDateInstance(DateFormat.MEDIUM);
		String s=format.format(date);
		String path=storePath + "\\" + s + "\\" + username;
		// 假如这个文件夹不存在，就创建一个文件夹
		File file=new File(path);
		if(!file.exists()) {
			file.mkdirs();
		}
		return path;
	}
	//查找所有视频
	@RequestMapping("/findVideoList")
	public ModelAndView findVideoList() {
	   List<Video> videoList = videoService.find();
	   return new ModelAndView("/page/my_space","videoList",videoList);
	}
	//根据上传时间和点击量查找视频
	@RequestMapping("/findByNumberAndTime")
	public String findByNumberAndTime(Model model,int categoryId,int isCharge,int categoryId2) {
		List<Video> RecentVideoList = videoService.findByNumberAndTime();
		model.addAttribute("RecentVideoList",RecentVideoList);
		
		List<Video> categoryIdList = videoService.findByCategoryId(categoryId);
		model.addAttribute("categoryIdList",categoryIdList);
		
		List<Video> chargeList = videoService.findByisCharge(isCharge);
		model.addAttribute("chargeList",chargeList);
		
		List<Video> categoryList = videoService.findByCategoryId(categoryId2);
		model.addAttribute("categoryList",categoryList);
		
		return "/page/index";
	}
	//根据关键字进行模糊查询
	@RequestMapping("/findByName")
	public String findByName(Model model,String content,Integer id, HttpServletRequest request)
	{  
		if(content != null) {
			request.getSession().setAttribute("content", content);
		} else {
			content = (String) request.getSession().getAttribute("content");
		}
		String sortName="/findByName";
		int index =1;
		if(id != null)
		{
			index=id;
		}
	    PageUtil<Video> pageUtil = videoService.findByName(content, index, 10);
	    model.addAttribute("sortName",sortName);
		model.addAttribute("pageUtil",pageUtil);
		return "/page/search";
	}
	
	@RequestMapping(value="/find",method=RequestMethod.GET)
	public void find(Model model)
	{ 
		List<Video> list = videoService.find();
		model.addAttribute("list",list);
	}
	//日期排序
	@RequestMapping("/sort")
	public String findBySort(Model model,Integer id)
	{
		String sortName="/sort";
		int index =1;
		if(id != null)
		{
			index=id;
		}
		 PageUtil<Video> pageUtil = videoService.findByDateSort(index, 10);
		model.addAttribute("pageUtil",pageUtil);
		model.addAttribute("sortName",sortName);
		return "/page/search";
	}
	//点击量排序
	@RequestMapping("/videoClick")
	public String findByVideoClick(Model model,Integer id) {
		String sortName="/videoClick";
		int index =1;
		if(id != null)
		{
			index=id;
		}
		 PageUtil<Video> pageUtil = videoService.findByVideoClick(index, 10);
		 model.addAttribute("pageUtil",pageUtil);
		 model.addAttribute("sortName",sortName);
		return "/page/search";
	}
	
	//跳转到上传视频页面前的准备工作
	@RequestMapping("/to_upload")
	public String to_upload(HttpServletRequest request, Model model) {
		//int userId = (int) request.getSession().getAttribute("userId");
		String username = (String) request.getSession().getAttribute("username"); //获取当前登陆的用户
		Users user = usersService.findByUserName(username);
		List<Category> categorys = categoryService.find();
		List<VideoList> videoLists = videoListService.findListByUserId(user.getId());
		//设置传递数据
		model.addAttribute("categorys", categorys);
		model.addAttribute("videoLists", videoLists);
		return "/page/video_upload";
		
	}
	
	//跳转到视频播放页面
	@RequestMapping("/to_play_video/{videoId}")
	public String to_play_video(Model model, @PathVariable("videoId") int videoId, HttpServletRequest request) {
		if(request.getSession().getAttribute("havesee") == null) {  //记录点击量
			List<Integer> havesee = new ArrayList<>();              
			request.getSession().setAttribute("havesee", havesee); 
		}
		List<Integer> havesee = (List<Integer>) request.getSession().getAttribute("havesee");  //获取点击量
		if(!havesee.contains(videoId)) {    //判断该视频是否点击过
			havesee.add(videoId);
			videoService.updateVideoClick(videoId);   //如果没有点击过，改变点击量
			videoService.updateVideoClick2(videoId);   //如果没有点击过，改变点击量
			
		}
		
		System.out.println(videoId);
		Video video = videoService.findById(videoId);
		List<Video> rands = videoService.findByRand();
		if(video.getVideoList() == null) {  //判断此此视频是否为播单
			PageUtil<Comment> commentPage = commentService.fingByVideoId(videoId, 1, 5);
			
			//设置数据
			model.addAttribute("rands", rands);
			model.addAttribute("video", video);
			model.addAttribute("commentPage", commentPage);
			//判断视频是直播还是点播
			if(video.getIsLive() == 1) {
				return "/page/play_video_rtmp";
			} else {
				return "/page/play_video";
			}
		} else {
			return "redirect:/video/to_play_video/list/" + video.getVideoList().getId();
		}
	}
	
	//跳转到播单播放页面
	@RequestMapping("/to_play_video/list/{listId}")
	public String to_play_video_list(Model model, @PathVariable("listId") int listId) {
		PageUtil<Comment> commentPage = commentService.findByListId(listId, 1, 5);
		List<Video> videos = videoService.findByListId(listId);
		List<Video> rands = videoService.findByRand();    //随机10个视频
		
		System.out.println("进入播单页面" + videos.size());
		
		Video video = videos.get(0);
		model.addAttribute("rands", rands);
		model.addAttribute("thisvideo", video);
		model.addAttribute("videos", videos);
		model.addAttribute("commentPage", commentPage);
		
		return "/page/play_video_list";
	}
	
	//ajax处理一个视频无刷新页面
	@RequestMapping("/to_ajax_video")
	public void to_ajax_video(int videoId, HttpServletResponse response) {
		System.out.println("ajax_come");
		System.out.println(videoId);
		Video video = videoService.findById(videoId);
		Map<String, String> videoMsg = new HashMap<String, String>();
		videoMsg.put("name", video.getName());
		videoMsg.put("videoClick", String.valueOf(video.getVideoClick()));
		videoMsg.put("url", video.getUrl());
		videoMsg.put("id", String.valueOf(video.getId()));
		
	
		//将json所需的包放到lib里面,将list转换为json
		//如果只是一个对象用JSONObject，如果是集合用JSONArray
		JSONObject json=JSONObject.fromObject(videoMsg);
		//响应前台页面
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/json");
 
		PrintWriter out;
		try {
			out = response.getWriter();
			out.println(json);//打印json,为了前台页面获取
			out.flush();//刷新流
			out.close();//关闭流 
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	//展示排行榜
	@RequestMapping("/rank")
	public String rank_view(Model model) {
		List<Video> video_click = videoService.findByTopClick();
		List<Video> video_recom = videoService.findByRecommend();
		List<Users> users = usersService.findByTopPoint();
		model.addAttribute("clicks", video_click);
		model.addAttribute("recomms", video_recom);
		model.addAttribute("users", users);
		return "/page/rank";
	}
	
	
	//根据视频分类id获取内容
	@RequestMapping("/category/{categoryId}")
	public String category_video(Model model,@PathVariable("categoryId") String categoryId) {
		int id = Integer.parseInt(categoryId);
		Category category = categoryService.findById(id);
		List<Video> list = videoService.findByCategoryIdAll(id);
		model.addAttribute("categoryList", list);
		model.addAttribute("category", category);
		
		return "page/movies";
		
	}
	
}
